package com.mo.utils;

import com.mo.entity.Menu;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class MenuTreeUtil {
    // 先构建第一层
    public static List<Menu> builderMenuTree(List<Menu> menus, Integer parentId) {
        return menus.stream()
                .filter(menu -> menu.getParentId().equals(parentId))
                .map(menu -> menu.setChildren(getChildren(menu, menus)))
                .collect(Collectors.toList());
    }

    // 递归构建所有层级
    private static List<Menu> getChildren(Menu menu, List<Menu> menus) {
        return menus.stream()
                .filter(m -> m.getParentId().equals(menu.getMenuId()))
                .map(m -> m.setChildren(getChildren(m, menus)))
                .collect(Collectors.toList());
    }

    // momo
    public static List<Menu> builderMenuTree2(List<Menu> menus, Integer parentId) {
        ArrayList<Menu> list = new ArrayList<>();
        menus.stream()
                .filter(menu -> menu.getParentId().equals(parentId))
                .forEach(child -> {
                    child.setChildren(builderMenuTree2(menus, child.getMenuId()));
                    list.add(child);
                });
        return list;
    }
}
